import { View, Text, Input, ScrollView } from '@tarojs/components'
import Taro, { useShareAppMessage } from '@tarojs/taro'
import { useState } from 'react'
import { useFormulas } from 'src/hooks/useFormulas'
import { useMixIngredient } from 'src/hooks/useMixIngredients'

import './index.less'

function Formula() {
  const params = Taro.getCurrentInstance().router?.params
  const id = params?.id
  const [formulas] = useFormulas(id)
  const [mixIngredient] = useMixIngredient(id)
  const [valueMap, setValueMap] = useState({} as any)
  const [hasScroll, setHasScroll] = useState(false)

  useShareAppMessage(() => {
    return {
      title: '配方',
      path: `/pages/formula/index?id=${id}`,
    }
  })

  const handleInput = (formulaId) => {
    return (e) => {
      let v = e.detail.value

      const isValue = /^\d+\.?(\d{1,6})?$/.test(v)

      // 当前配料
      const current = formulas.find(i => i.id === formulaId)
      let value

      if (v === '') {
        value = 0
      } else {
        // 禁止非数字输入
        if (!isValue) {
          v = valueMap[formulaId]
        }
  
        value = Number(v)
      }    

      const map = { ...valueMap, [formulaId]: v }

      // 如果当前配料不存在，直接返回
      if (current) {
        // 计算当前配料一个单位的量
        const unitValue = value / current.rate!
  
        // 计算配方
        formulas.forEach(item => {
          if (item.id === formulaId) {
            return
          }
          // 保留六位小数
          map[item.id!] = Math.round(unitValue * item.rate! * 1000000) / 1000000
        })
      }

      setValueMap(map)
    }
  }

  const handleScroll = (e) => {
    console.log(e)
    if (e.detail.scrollTop < 20) {
      setHasScroll(false)
    } else {
      setHasScroll(true)
    }
  }

  const handleScrollTop = () => {
    setHasScroll(false)
  }

  return (
    <View className='formula'>
      <View className='header'>
        <View className='header-name'>{mixIngredient?.name}</View>
        <View className='header-label'>配方</View>
      </View>
      <View className='body'>
        {
          !!mixIngredient?.remark &&
          <View className='formula-remark'>
            {mixIngredient?.remark}
          </View>
        }
        <ScrollView
          className={`formula-list-scroll ${hasScroll ? 'has-scroll' : ''}}`}
          scrollY
          scrollWithAnimation
          onScroll={handleScroll}
          onScrollToUpper={handleScrollTop}
        >
          <View className='formula-list'>
            {
              (formulas || []).map((itemData, i) => (
                <View className='formula-item' key={i}>
                  <View className='formula-item-name'>
                    {itemData.baseIngredient?.name}
                    {
                      !!itemData.remark &&
                      <View className='formula-item-remark'>{itemData.remark}</View>
                    }
                  </View>
                  <View className='formula-value'>
                    <Input
                      className='formula-value-input'
                      type='number'
                      placeholder='请输入需求量'
                      value={valueMap[itemData.id!]}
                      onInput={handleInput(itemData?.id)}
                      placeholderStyle='font-size: 28rpx; color: #C5C5C5;'
                      controlled
                    />
                    <Text className='formula-value-unit'>{itemData?.baseIngredient?.unit}</Text>
                  </View>
                </View>
              ))
            }
          </View>
        </ScrollView>
      </View>
    </View>
  );
}

export default Formula;
